<template>
  <div class="invoice-list-container">
    <el-card class="list-card">
      <template #header>
        <div class="card-header">
          <h2>
            <el-icon><Money /></el-icon>
            待开票信息列表
          </h2>
          <div class="header-actions">
            <el-button @click="refreshList" type="primary">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
            <el-button @click="createNewInvoice" type="success">
              <el-icon><Plus /></el-icon>
              新建发票
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索和筛选 -->
      <div class="search-section">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input
              v-model="searchForm.keyword"
              placeholder="搜索客户名称或发票号"
              clearable
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-select v-model="searchForm.status" placeholder="状态筛选" clearable>
              <el-option label="待开票" value="pending" />
              <el-option label="已开票" value="completed" />
              <el-option label="已取消" value="cancelled" />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-col>
          <el-col :span="4">
            <el-button @click="handleSearch" type="primary">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="resetSearch">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-col>
        </el-row>
      </div>

      <!-- 数据表格 -->
      <div class="table-section">
        <el-table
          :data="invoiceList"
          v-loading="loading"
          stripe
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="invoiceNumber" label="发票号" width="140" />
          <el-table-column prop="customerName" label="客户名称" min-width="150" />
          <el-table-column prop="customerTaxNumber" label="纳税人识别号" width="160" />
          <el-table-column prop="totalAmount" label="金额" width="120">
            <template #default="{ row }">
              <span class="amount-text">¥{{ row.totalAmount.toFixed(2) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="taxAmount" label="税额" width="120">
            <template #default="{ row }">
              <span class="amount-text">¥{{ row.taxAmount.toFixed(2) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="totalWithTax" label="价税合计" width="120">
            <template #default="{ row }">
              <span class="amount-text total">¥{{ row.totalWithTax.toFixed(2) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)">
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="160">
            <template #default="{ row }">
              {{ formatDate(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button @click="viewDetail(row)" size="small">
                <el-icon><View /></el-icon>
                查看
              </el-button>
              <el-button 
                v-if="row.status === 'pending'"
                @click="editInvoice(row)" 
                size="small" 
                type="primary"
              >
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <el-button 
                v-if="row.status === 'pending'"
                @click="confirmInvoice(row)" 
                size="small" 
                type="success"
              >
                <el-icon><Check /></el-icon>
                开票
              </el-button>
              <el-button 
                v-if="row.status === 'pending'"
                @click="deleteInvoice(row)" 
                size="small" 
                type="danger"
              >
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 发票详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="发票详情"
      width="80%"
      :before-close="handleDetailClose"
    >
      <div class="invoice-detail" v-if="selectedInvoice">
        <div class="detail-section">
          <h3>基本信息</h3>
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="detail-item">
                <label>发票号：</label>
                <span>{{ selectedInvoice.invoiceNumber }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="detail-item">
                <label>状态：</label>
                <el-tag :type="getStatusType(selectedInvoice.status)">
                  {{ getStatusText(selectedInvoice.status) }}
                </el-tag>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="detail-item">
                <label>创建时间：</label>
                <span>{{ formatDate(selectedInvoice.createTime) }}</span>
              </div>
            </el-col>
          </el-row>
        </div>

        <div class="detail-section">
          <h3>客户信息</h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="detail-item">
                <label>客户名称：</label>
                <span>{{ selectedInvoice.customerName }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <label>纳税人识别号：</label>
                <span>{{ selectedInvoice.customerTaxNumber }}</span>
              </div>
            </el-col>
          </el-row>
        </div>

        <div class="detail-section">
          <h3>商品信息</h3>
          <el-table :data="selectedInvoice.goods" border>
            <el-table-column prop="name" label="商品名称" />
            <el-table-column prop="specification" label="规格型号" />
            <el-table-column prop="unit" label="单位" />
            <el-table-column prop="quantity" label="数量" />
            <el-table-column prop="unitPrice" label="单价">
              <template #default="{ row }">
                ¥{{ row.unitPrice.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column prop="amount" label="金额">
              <template #default="{ row }">
                ¥{{ row.amount.toFixed(2) }}
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div class="detail-section">
          <h3>金额汇总</h3>
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="detail-item">
                <label>商品总金额：</label>
                <span>¥{{ selectedInvoice.totalAmount.toFixed(2) }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="detail-item">
                <label>税额：</label>
                <span>¥{{ selectedInvoice.taxAmount.toFixed(2) }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="detail-item">
                <label>价税合计：</label>
                <span class="total-amount">¥{{ selectedInvoice.totalWithTax.toFixed(2) }}</span>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailVisible = false">关闭</el-button>
          <el-button 
            v-if="selectedInvoice?.status === 'pending'"
            @click="editInvoice(selectedInvoice)" 
            type="primary"
          >
            编辑
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'

// 接口定义
interface InvoiceItem {
  id: string
  invoiceNumber: string
  customerName: string
  customerTaxNumber: string
  totalAmount: number
  taxAmount: number
  totalWithTax: number
  status: 'pending' | 'completed' | 'cancelled'
  createTime: string
  goods: Array<{
    name: string
    specification: string
    unit: string
    quantity: number
    unitPrice: number
    amount: number
  }>
}

interface SearchForm {
  keyword: string
  status: string
  dateRange: [string, string] | null
}

interface Pagination {
  currentPage: number
  pageSize: number
  total: number
}

// 路由
const router = useRouter()

// 响应式数据
const loading = ref(false)
const detailVisible = ref(false)
const selectedInvoice = ref<InvoiceItem | null>(null)
const selectedRows = ref<InvoiceItem[]>([])

// 搜索表单
const searchForm = reactive<SearchForm>({
  keyword: '',
  status: '',
  dateRange: null
})

// 分页
const pagination = reactive<Pagination>({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 发票列表数据
const invoiceList = ref<InvoiceItem[]>([])


// 方法
const generateMockData = (): InvoiceItem[] => {
  const mockData: InvoiceItem[] = []
  const statuses: Array<'pending' | 'completed' | 'cancelled'> = ['pending', 'completed', 'cancelled']
  const customers = ['北京科技有限公司', '上海贸易有限公司', '深圳电子有限公司', '广州制造有限公司', '杭州软件有限公司']

  for (let i = 1; i <= 50; i++) {
    const totalAmount = Math.random() * 10000 + 1000
    const taxRate = 0.13
    const taxAmount = totalAmount * taxRate
    const totalWithTax = totalAmount + taxAmount

    mockData.push({
      id: `invoice_${i}`,
      invoiceNumber: `INV${String(i).padStart(6, '0')}`,
      customerName: customers[Math.floor(Math.random() * customers.length)],
      customerTaxNumber: `91110000MA${String(Math.floor(Math.random() * 100000000)).padStart(8, '0')}${String(Math.floor(Math.random() * 10000)).padStart(4, '0')}`,
      totalAmount,
      taxAmount,
      totalWithTax,
      status: statuses[Math.floor(Math.random() * statuses.length)],
      createTime: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString(),
      goods: [
        {
          name: `商品${i}`,
          specification: '标准版',
          unit: '件',
          quantity: Math.floor(Math.random() * 10) + 1,
          unitPrice: totalAmount / (Math.floor(Math.random() * 10) + 1),
          amount: totalAmount
        }
      ]
    })
  }

  return mockData
}

const loadInvoiceList = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    invoiceList.value = generateMockData()
    pagination.total = invoiceList.value.length
  } catch (error) {
    ElMessage.error('加载发票列表失败')
  } finally {
    loading.value = false
  }
}

const refreshList = () => {
  loadInvoiceList()
}

const createNewInvoice = () => {
  router.push('/invoice/form')
}

const handleSearch = () => {
  pagination.currentPage = 1
  // 这里可以调用API进行搜索
  ElMessage.success('搜索完成')
}

const resetSearch = () => {
  searchForm.keyword = ''
  searchForm.status = ''
  searchForm.dateRange = null
  pagination.currentPage = 1
}

const handleSelectionChange = (selection: InvoiceItem[]) => {
  selectedRows.value = selection
}

const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.currentPage = 1
}

const handleCurrentChange = (page: number) => {
  pagination.currentPage = page
}

const viewDetail = (invoice: InvoiceItem) => {
  selectedInvoice.value = invoice
  detailVisible.value = true
}

const editInvoice = (invoice: InvoiceItem) => {
  router.push({
    path: '/invoice/form',
    query: { id: invoice.id }
  })
}

const confirmInvoice = (invoice: InvoiceItem) => {
  router.push({
    path: '/invoice/confirm',
    query: { id: invoice.id }
  })
}

const deleteInvoice = async (invoice: InvoiceItem) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除发票 ${invoice.invoiceNumber} 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 模拟删除操作
    const index = invoiceList.value.findIndex(item => item.id === invoice.id)
    if (index > -1) {
      invoiceList.value.splice(index, 1)
      pagination.total--
    }
    
    ElMessage.success('删除成功')
  } catch {
    // 用户取消删除
  }
}

const handleDetailClose = () => {
  detailVisible.value = false
  selectedInvoice.value = null
}

const getStatusType = (status: string) => {
  const typeMap: Record<string, string> = {
    pending: 'warning',
    completed: 'success',
    cancelled: 'danger'
  }
  return typeMap[status] || 'info'
}

const getStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    pending: '待开票',
    completed: '已开票',
    cancelled: '已取消'
  }
  return textMap[status] || '未知'
}

const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

// 生命周期
onMounted(() => {
  loadInvoiceList()
})
</script>

<style scoped>
.invoice-list-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.list-card {
  max-width: 1400px;
  margin: 0 auto;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  border-radius: 12px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 10px;
}

.card-header h2 {
  margin: 0;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 24px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-section {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.table-section {
  margin-bottom: 20px;
}

.pagination-section {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

.amount-text {
  font-weight: 600;
  color: #303133;
}

.amount-text.total {
  color: #e6a23c;
  font-size: 16px;
}

.invoice-detail {
  padding: 20px 0;
}

.detail-section {
  margin-bottom: 30px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.detail-section h3 {
  margin: 0 0 20px 0;
  color: #303133;
  font-size: 18px;
  font-weight: 600;
  border-bottom: 2px solid #409eff;
  padding-bottom: 10px;
}

.detail-item {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.detail-item label {
  font-weight: 600;
  color: #606266;
  min-width: 120px;
  margin-right: 10px;
}

.detail-item span {
  color: #303133;
}

.total-amount {
  font-weight: 600;
  color: #e6a23c;
  font-size: 16px;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 15px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .invoice-list-container {
    padding: 10px;
  }
  
  .card-header {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }
  
  .header-actions {
    justify-content: center;
  }
  
  .search-section .el-col {
    margin-bottom: 10px;
  }
  
  .detail-section {
    padding: 15px;
  }
  
  .detail-item {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .detail-item label {
    margin-bottom: 5px;
  }
}

@media (max-width: 480px) {
  .search-section {
    padding: 15px;
  }
  
  .detail-section {
    padding: 10px;
  }
}
</style>
